package com.hmdp.service.impl;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.hmdp.entity.ShopType;
import com.hmdp.exception.WebException;
import com.hmdp.mapper.ShopTypeMapper;
import com.hmdp.service.IShopTypeService;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.concurrent.TimeUnit;

import static com.hmdp.utils.RedisConstants.CACHE_SHOP_TYPE_KEY;
import static com.hmdp.utils.RedisConstants.CACHE_SHOP_TYPE_TTL;

/**
 * <p>
 * 服务实现类
 * </p>
 *
 * @author 虎哥
 * @since 2021-12-22
 */

@Slf4j
@RequiredArgsConstructor
@Service
public class ShopTypeServiceImpl extends ServiceImpl<ShopTypeMapper, ShopType> implements IShopTypeService {

    private final RedisTemplate<String, Object> redisTemplate;

    @Override
    public List<? extends Object> selectShopTypeList() {
        List<Object> cacheData = redisTemplate.opsForList().range(CACHE_SHOP_TYPE_KEY, 0, -1);
        if (cacheData != null && !cacheData.isEmpty()) {
            return cacheData.stream()
                    .map(obj -> (ShopType) obj)
                    .toList();
        }

        List<ShopType> list = super.query().orderByAsc("sort").list();
        if (list.isEmpty()) {
            throw new WebException("请稍后重试...");
        }

        redisTemplate.opsForList().leftPushAll(CACHE_SHOP_TYPE_KEY, list.toArray());
        redisTemplate.expire(CACHE_SHOP_TYPE_KEY, CACHE_SHOP_TYPE_TTL, TimeUnit.MINUTES);

        return list;
    }
}
